# -*- coding:utf-8 -*-
the_day = '20210820'  #截至计算时间
import sys
from ntpath import join
import time
import copy
import tushare as ts
import datetime
from datetime import timedelta

import pandas as pd
from SNetwork.StockSQL import StockSQL
from SChart.StockChart import StockChart
from SData.StockHtmlTool import StockHtmlTool
from SChart.StockMT import StockMT
from SChart.StockAccount import StockAccount
from SChart.StockDataManager import StockDataManager

from STool.StockTT import *
from STool.StockTool import StockTool
from SDaily.StockYearHigh import StockYearHigh
from SDaily.StockSingle import StockSingle
from stock_py.SysFile import Base_File_Oper

from stock_py.HtmlToEmail import htmlViewTool

STOCK_BK_RPS5=None
Today_string= StockTool.getTodayString()



def PPivot(stocks):
    stock_ppivot= mt_obj.PPivot(stocks)
    ts_codes = stock_ppivot.ts_code.values
    ts_names = stock_ppivot.name.values

    koudai_stocks_codenames=[]
    for index,th_code in enumerate(ts_codes):
        koudai_stocks_codenames.append(th_code+" "+ts_names[index])
        
    print("获取符合 口袋支点 股票数据 %s" %(len(koudai_stocks_codenames)))
    print(koudai_stocks_codenames)
    print("\n")
    StockHtmlTool.buildCustomContent("口袋支点股票"," ".join(koudai_stocks_codenames))
    
def RPS5(pd_stock_rps):
    stock_singleObjc = StockSingle()

    pd_stock_rps5 = pd_stock_rps[pd_stock_rps['rps5']>=85]
    stock_bk_rps5 = mt_obj.BKPower(pd_stock_rps5)
    dataManager.dealBKDataToSql(stock_bk_rps5)
    
    [stock_table,stock_valid_rps5,stock_table_98]= stockChart_obj.buildStocksMaAndMt(pd_stock_rps5,stock_bk_rps5,5)
    StockHtmlTool.buildCustomContent("RPS5 动量板块数据 ")
    StockHtmlTool.buildCustomContent(" ".join([ bankuai+":"+format(mt,'.2%') for bankuai,mt in stock_bk_rps5.items()]))
    StockHtmlTool.buildCustomContent("*********************************************************")
    StockHtmlTool.buildStocklData(stock_valid_rps5,stock_bk_rps5,5)
    
    print("RPS5 动量板块数据值大于 96 共%s 只" %(len(stock_table_98)))
    StockHtmlTool.buildCustomContent("RPS5 动量板块数据值大于 96 共%s 只" %(len(stock_table_98)))
    aa = [item['symbol']for item in stock_table_98]
    stock_singleObjc.RPS5_CODES=aa
    StockHtmlTool.buildCustomContent(" ".join(aa))
    StockHtmlTool.buildJSDataToSQL(stock_table,"rps5")


def RPS3(pd_stock_rps):
    stock_singleObjc = StockSingle()

    pd_stock_rps5 = pd_stock_rps[pd_stock_rps['rps3']>=85]
    stock_bk_rps5 = mt_obj.BKPower(pd_stock_rps5)


    StockHtmlTool.buildCustomContent("RPS3 动量板块数据 ")
    StockHtmlTool.buildCustomContent(" ".join([ bankuai+":"+format(mt,'.2%') for bankuai,mt in stock_bk_rps5.items()]))
    StockHtmlTool.buildCustomContent("*********************************************************")
    
    StockHtmlTool.buildCustomContent("RPS3 >=85 股票数据 ")
    [stock_table,stock_valid_rps5_array,stock_table_95]= stockChart_obj.buildStocksMaAndMt(pd_stock_rps5,stock_bk_rps5,3)
    StockHtmlTool.buildStocklData(stock_valid_rps5_array,stock_bk_rps5,3)
    
    print("RPS3 >=95 股票数据 共%s 只" %(len(stock_table_95)))
    StockHtmlTool.buildCustomContent("RPS3 >=95 股票数据  共%s 只" %(len(stock_table_95)))
    aa = [item['symbol']for item in stock_table_95]
    stock_singleObjc.RPS3_CODES=aa
    StockHtmlTool.buildCustomContent(" ".join(aa))
    StockHtmlTool.buildJSDataToSQL(stock_table,"rps3")
    StockHtmlTool.buildCustomContent(" ")
    StockHtmlTool.buildCustomContent(" ")
    StockHtmlTool.buildCustomContent(" ")


    
def RPS20(pd_stock_rps):
    stock_singleObjc = StockSingle()
    stock_rps20 = pd_stock_rps[pd_stock_rps['rps20']>=90]
    stock_bk_rps20 = mt_obj.BKPower(stock_rps20)
    [stock_table,stock_valid_rps20,stock_table_98] = stockChart_obj.buildStocksMaAndMt(stock_rps20,stock_bk_rps20,20)
    # StockHtmlTool.buildCustomContent("RPS20 动量板块数据 ")
    # StockHtmlTool.buildCustomContent(" ".join([ bankuai+":"+format(mt,'.2%') for bankuai,mt in stock_bk_rps20.items()]))
    # StockHtmlTool.buildCustomContent("*********************************************************")
    # StockHtmlTool.buildStocklData(stock_valid_rps20,stock_bk_rps20,20)
    # StockHtmlTool.buildJSDataToSQL(stock_table,"rps20")
    
    aa = [item['symbol']for item in stock_table_98]
    stock_singleObjc.RPS20_CODES=aa



# 全部的rps输出表格，已基础过滤，可选的手动过滤
def RPSAll(pd_stock_rps):
    stock_singleObjc = StockSingle()

    stock_ppivot = mt_obj.PPivot(pd_stock_rps)
    # pd_stock_rps3 = pd_stock_rps[pd_stock_rps['rps3'] >= 85] #620个
    # pd_stock_rps5 = pd_stock_rps[pd_stock_rps['rps5'] >= 85] #620个
    # pd_stock_rps3and5 = pd_stock_rps[(pd_stock_rps['rps5'] >= 85) & (pd_stock_rps['rps3'] >= 85)] #300多

    # 逻辑或，rps3或者rps5的都入选，自己在表格里面筛选，叠加
    pd_stock_rps3and5 = pd_stock_rps[(pd_stock_rps['rps5'] >= 85) | (pd_stock_rps['rps3'] >= 85)| (pd_stock_rps['rps20'] >= 85)] #800多

    #拿到rps3-5-20，保留需要的列
    cols_to_keep = ['symbol', 'name', 'hy', 'hy2', 'rps3', 'rps5', 'rps20','huanshou','circ_mv']
    df_data = pd_stock_rps3and5[cols_to_keep]

    df_data.loc[df_data['rps3'] < 85, 'rps3'] = 'X85' #修改某一列的值大于等于85
    df_data.loc[df_data['rps5'] < 85, 'rps5'] = 'X85' #修改：小于85的一律显示X85
    df_data.loc[df_data['rps20'] < 85, 'rps20'] = 'X85'
    # 基础配置大于40亿，小于50亿就是40-50亿之间显示Y40，大于50亿就显示实际的保留2位小数
    df_data["circ_mv"] = np.where(df_data["circ_mv"] < 50.0, 'Y40', df_data['circ_mv'].map(lambda x: f'{x:,.2f}'))

    df_data.insert(loc=9,column='topHigh120',value=0 ) #增加两列
    df_data.insert(loc=10, column='topHigh250', value=0)
    df_data.insert(loc=11, column='koudai', value=0)

    # df_data["koudai"] = np.where(df_data["symbol"] in koudaiList, 'KD', 0)
    df_data['koudai'] = [(item in stock_ppivot.symbol.values and 1 or 0) for item in df_data.symbol.values]

    # 数据在trade_daily里面,不做回测的话就不用保存每天的topHigh120，放外面就一条数据
    trade_daily = pd_stock_rps3and5.trade_daily.values
    top120 = [round((item[0]['close']/item[0]['topHigh120']) ,3) for item in trade_daily]
    df_data['topHigh120'] = top120

    top250 = [round((item[0]['close']/item[0]['topHigh250']) ,3) for item in trade_daily]
    df_data['topHigh250'] = top250

    #小于0.95的替换成空
    df_data.loc[df_data['topHigh120'] < 0.95, 'topHigh120'] = 0
    df_data.loc[df_data['topHigh250'] < 0.95, 'topHigh250'] = 0


    # 对两列同时按照升序排列
    df_data.sort_values(by=['hy', 'hy2'], inplace=True, ascending=True)

    print(df_data)
    now_hour = datetime.datetime.now().hour
    # 当前时间大于15点才显示当天的，否则日期改成昨天的
    if now_hour >= 15:
        date_str = datetime.datetime.now().strftime('%y-%m-%d')
    else:
        date_str = (datetime.datetime.today() + timedelta(days=-1)).strftime("%y-%m-%d")
    filename = f"{date_str}-全部的rps"
    Base_File_Oper.save_patten_analysis(df_data, filename)

    print("完成了，表格输出在：stock_pjo/ConfigFileInput/csvDataOutput")

    df_dataPass = df_data
    df_dataPass = df_dataPass[(df_dataPass['rps3'] != "X85") & (df_dataPass['rps5'] != "X85")]
    df_dataPass = df_dataPass[(df_dataPass['topHigh120'] > 0.9)] #过滤为空的
    aaa = df_dataPass.columns.values
    #发送邮件
    htmlViewTool.build_html_view(f"{date_str}-筛选数据",aaa,df_dataPass.values,filename)

    print(len(df_dataPass))
    codeAll = ''
    for row in df_dataPass.values:
        codeAll = codeAll+row[0]+','

    print(codeAll)
    
def ZMA100 (pd_stock_rps):
    stock_singleObjc = StockSingle()

    stocks = stockChart_obj.buildStocksMaAndMtMA100(pd_stock_rps,stock_singleObjc.stock_bk_rps)
    StockHtmlTool.buildCustomContent("MA100股票数据 %s 只"%(len(stocks)) )
    StockHtmlTool.buildCustomContent("*********************************************************")
    aa="  ".join(stocks)	
    StockHtmlTool.buildCustomContent(aa)

def RPS_gongzhen():
    print("RPS3 5 20共振")
    stock_singleObjc = StockSingle()
    
    for item in stock_singleObjc.RPS3_CODES:
        if item in stock_singleObjc.RPS5_CODES :
            print(item)
            
    


if __name__ == '__main__':    
    
    start_time = time.time()
    stock_singleObjc = StockSingle()
    curr_time = datetime.datetime.now()
    hour=curr_time.hour
    #更新本地数据库
    #1、获取最新股票库和交易数据
    # print("开始获取当日最新数据")
    ts.set_token(Base_File_Oper.read_tushare_token())
    pro = ts.pro_api()
    df = pro.trade_cal(exchange='', start_date='20220101',end_date=datetime.datetime.now().strftime('%Y%m%d'), is_open='1')
    if hour>=0 and hour<16:
        current_trade_date = df.to_dict(orient='records')[-2]['cal_date']
    else:
        current_trade_date = df.to_dict(orient='records')[-1]['cal_date']
    current_trade_date = df.to_dict(orient='records')[-1]['cal_date']

    stock_singleObjc.trade_date_now = current_trade_date
    print("最新交易日期 %s" %(stock_singleObjc.trade_date_now))
    print("最新数据文件 %s" %(stock_singleObjc.trade_stock_now_file_path))
    StockHtmlTool.buildCustomContent("=============================================")
    StockHtmlTool.buildCustomContent("附加条件：流通市值大于>100;上市>1年;行业最高rps>95;")
    StockHtmlTool.buildCustomContent("=============================================")


    print("开始获取当日最新数据")
    
    stockSQL=StockSQL()  
    mt_obj = StockMT(stockSQL)
    stockChart_obj =StockChart(stockSQL)
    yearHigh=StockYearHigh(stockSQL)
    dataManager=StockDataManager(stockSQL)
    
    # print("开始计算一年新高")
    # yearHigh.remarkYearHigh()
    
    print("开始计算RPS股票池")
    pd_all_stocks=stockSQL.searchStockForJijinAndHK(2)
    pd_stock_rps=mt_obj.RPS(pd_all_stocks) #所有股票的RPS   
    
    RPS3(pd_stock_rps)

    RPS5(pd_stock_rps)
    
    RPS20(pd_stock_rps)
    
    #上面的输出txt，这个输出表格，自己在表格二次筛选
    RPSAll(pd_stock_rps)

    # RPS_gongzhen()


    # stockSQL.searchBM_MT()




        # pd_all_stocks_3=stockSQL.searchStockForMA100()
    # print("开始计算均线100股票池")
    # ZMA100(pd_all_stocks_3)


    # #涨停股
    # zhangting = stockSQL.searchZhangTing()
    # zhangting_array = list(zhangting['symbol'])
    # print("今日相对昨日新增涨停 共%s 只" %(len(zhangting_array)))
    # print(zhangting_array)
    # StockHtmlTool.buildCustomContent("今日相对昨日新增涨停 共%s 只" %(len(zhangting_array)))
    # StockHtmlTool.buildCustomContent(" ".join(zhangting_array))

